package be.kuleuven.mume.beans;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import be.kuleuven.mume.PMF;
import be.kuleuven.mume.exceptions.UserNotLoggedInException;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class PriorityBean {
	private double priority;
	private Key persoon;
	private Key object;

	public static int standardPriority(int type) {
		return type;
	}
	
	public static class type{
		public static final int DEADLINE = 5;
		public static final int TAAK = 4;
		public static final int TWEET = 0;
	}
	
	public void setPriority(double priority) {
		this.priority = priority;
	}

	public double getPriority() {
		return priority;
	}
	
	public void setPersoon(Key persoon){
		this.persoon = persoon;
	}
	
	public Key getPersoon(){
		return this.persoon;
	}

	public void setObject(Key object) {
		this.object = object;
	}

	public Key getObject() {
		return object;
	}
	
	public int convert() {
		return (int)Math.round(priority);
	}
	
	public void store(){
		
	}
	
	public static class PriorityFactory{
		public int getPriority(Key object, int type) throws UserNotLoggedInException{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			
			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
			
			if(user == null)
				throw new UserNotLoggedInException(userService.createLoginURL(""));
			
			String googleId = user.getUserId();
			Key persoon = KeyFactory.createKey(PersoonBean.class.getSimpleName(), googleId);
			
			Query q = pm.newQuery(PriorityBean.class);
			q.declareImports("import com.google.appengine.api.datastore.Key");
			q.setFilter("object == objectParam");
			q.setFilter("persoon == persoonParam");
			q.declareParameters("Key objectParam");
			q.declareParameters("Key persoonParam");
			
			@SuppressWarnings("unchecked")
			List<PriorityBean> prioritys = (List<PriorityBean>)q.execute(object, persoon);
			
			if(prioritys.size() == 0)
				return PriorityBean.standardPriority(type);
			assert prioritys.size() == 1;
			
			return prioritys.get(0).convert();
		}
	}
}
